<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable")
          ._table_header(slot="header")
            .table-title-lefttxt.pull-left
              span.leftText
                | 合计:
                span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
                | 条
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(v-if="hasViewDetail" type="text" size="small" @click="goToDetails(row.id)") 明细
            Button.mr-10(v-if="hasExport" type="text" size="small" @click="isExport(row.id, 'export')") 导出财务模板
            Button.mr-10(v-if="hasExportAxs" type="text" size="small" @click="handleExportAxs(row.id)") 导出安薪税工资模板
            Button(v-if="hasExportAxsEmployee" type="text" size="small" @click="handleExportAxsEmployee(row.id)") 导出安薪税员工模板
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    Modal(v-model="isShowExportAgainModal"
      title="提示"
      @on-ok="handleExportAgain"
    )
      p.text-center.font-16.pt-20.pb-20 {{isExportAgainModalTip}}
</template>

<script>
import { EnumApi } from '@/api/Enum.api.js'
import { FinanceBasedataApi } from '@/api/FinanceBasedata.api.js'
// import { BalanceApi } from '@/api/Balance.api.js'
import { ServersThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'

export default {
  name: '',

  components: {
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(ServersThead),
      tableData: [],
      formData: {
        customerName: '',
        orderNo: ''
      },
      formItem: [
        { type: 'input', label: '企业名称：', placeholder: '请输入企业名称', prop: 'customerName', model: 'customerName', options: 'customer', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'input', label: '流水号：', placeholder: '请输入流水号', prop: 'orderNo', model: 'orderNo', options: 'customer', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' }
      ],
      rules: {},
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        inServiceCount: 0, // 在职
        outServiceCount: 0 // 离职
      },
      downLoadRul: '',
      arrListDown: {
        customer: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      isShowExportAgainModal: false,
      isExportAgainModalTip: '',
      isExportAgainModalName: '',
      currentExportAgainModalId: null
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 明细
    hasViewDetail () {
      return this.actionArr.indexOf('ViewDetail') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 导出安薪税
    hasExportAxs () {
      return this.actionArr.indexOf('ExportAxs') > -1
    },
    // 导出安薪税员工
    hasExportAxsEmployee () {
      return this.actionArr.indexOf('ExportAxsEmployee') > -1
    }
  },

  watch: {
  },

  mounted () {
    this.query()
  },

  methods: {
    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        Status: 2,
        CustomerName: this.formData.customerName,
        OrderNo: this.formData.orderNo,
        CustomerId: this.$route.query.customerId,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await FinanceBasedataApi.getList(params)
      console.log('客户差额详情res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 去往详情
    goToDetails (id) {
      this.$router.push({
        path: '/unionPayFinancialDetails',
        name: 'unionPayFinancialDetails',
        query: {
          id: id
        }
      })
    },

    // 校验是否已经导出
    async isExport (id, str) {
      this.currentExportAgainModalId = id
      this.isExportAgainModalName = str
      let res = await FinanceBasedataApi.isExport({ id: id })
      console.log('校验是否已经导出res: ', res)
      if (res.status === 200 && res.data.success) {
        // if (str === 'exportAxs') {
        //   this.handleExportAxs(id)
        // } else {
        //   this.handleExport(id)
        // }
        this.handleExport(id)
      } else if (res.data.code === 'IsExport') {
        this.isShowExportAgainModal = true
        this.isExportAgainModalTip = res.data.message
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出财务模板
    handleExport (id) {
      console.log('导出财务模板')
      FinanceBasedataApi.export({ OrderId: id }).then(res => {
        let fileName = '财务模板.xlsx'
        let blob = new Blob([res.data], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          let objectUrl = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = fileName
          link.href = objectUrl
          link.click()
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
        this.searchFn()
      })
    },

    // 导出安薪税模板
    handleExportAxs (id) {
      console.log('导出安薪税模板')
      FinanceBasedataApi.exportAxs({ OrderId: id }).then(res => {
        let fileName = '安薪税模板.xls'
        let blob = new Blob([res.data], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          let objectUrl = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = fileName
          link.href = objectUrl
          link.click()
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
        this.searchFn()
      })
    },

    // 导出安薪税员工模板
    handleExportAxsEmployee (id) {
      console.log('导出安薪税员工模板')
      FinanceBasedataApi.exportAxsEmployee({ OrderId: id }).then(res => {
        let fileName = '安薪税员工模板.xls'
        let blob = new Blob([res.data], { type: 'application/octet-stream' })
        if ('download' in document.createElement('a')) {
          let objectUrl = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = fileName
          link.href = objectUrl
          link.click()
        } else {
          navigator.msSaveBlob(blob, fileName)
        }
        this.searchFn()
      })
    },

    handleExportAgain () {
      if (this.isExportAgainModalName === 'exportAxs') {
        this.handleExportAxs(this.currentExportAgainModalId)
      } else {
        this.handleExport(this.currentExportAgainModalId)
      }
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
